package com.dongpl.module.sysUser.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dongpl.module.sysUser.dao.SysUserMapper;
import com.dongpl.module.sysUser.entity.SysPerms;
import com.dongpl.module.sysUser.entity.SysRole;
import com.dongpl.module.sysUser.entity.SysUser;
import com.dongpl.module.sysUser.service.SysUserService;
import com.dongpl.module.sysUser.vo.RegisterUser;
import com.dongpl.utils.SaltUtil;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * 用户信息管理业务层实现
 * @author Administrator
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SysUserServiceImpl implements SysUserService {

    @Resource
    private SysUserMapper userMapper;

    @Override
    public void register(SysUser user) {
        //1.获取随机盐
        String salt = SaltUtil.getSalt(8);
        //2.将随机盐保存到数据
        user.setSalt(salt);
        //3.明文密码进行md5 + salt + hash散列
        Md5Hash mD5 = new Md5Hash(user.getPassword(),salt,1024);
        user.setPassword(mD5.toHex());
        user.setStatus(1);
        userMapper.insert(user);
    }

    @Override
    public SysUser findByUsername(String username) {
        if (StringUtils.isEmpty(username)){
            return new SysUser();
        }
        return userMapper.findByUsername(username);
    }

    @Override
    public SysUser findRoleByUsername(String username) {
        return userMapper.findRoleByUsername(username);
    }

    @Override
    public SysRole findPermByRoleId(String id) {
        return userMapper.findPermByRoleId(id);
    }

    @Override
    public List<SysPerms> findPermsByRoleId2(String id) {
        return userMapper.findPermsByRoleId2(id);
    }

    @Override
    public List<SysUser> getUserList() {
        return userMapper.selectList(new QueryWrapper<>());
    }

    @Override
    public Boolean registerUser(RegisterUser user) {
        SysUser sysUser = new SysUser();
        sysUser.setUsername(user.getUsername());
        //1.获取随机盐
        String salt = SaltUtil.getSalt(8);
        //2.将随机盐保存到数据
        sysUser.setSalt(salt);
        //3.明文密码进行md5 + salt + hash散列
        Md5Hash mD5 = new Md5Hash(user.getPassword(),salt,1024);
        sysUser.setPassword(mD5.toHex());
        sysUser.setStatus(1);
        int insert = userMapper.insert(sysUser);
        return insert > 0;
    }

}
